import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Image, 
  Dimensions,ScrollView,
  TouchableOpacity,
} from 'react-native';
import Orientation from 'react-native-orientation';
import RefreshListView, {RefreshState} from 'react-native-refresh-list-view';
import ImagePicker from 'react-native-image-crop-picker';
import SearchView from '../../component/SearchView';
import { TipModal } from '../../component/Tips';
import Loading from '../../component/Loading';
import BackButton from '../../component/BackButton';
import {jumpPage} from '../../common/common'
import {BASEURL} from '../../api/api'
import NoData from '../../component/NoData';
import HeaderTitle from '../../component/HeaderTitle';
import Search from './Search';
let {height, width} = Dimensions.get('window');
//var height=640,width=320;
const leftWidth = 100;
let width5 = (height-leftWidth-5*8)/7;
//height=640;
//width=320;
//height=738;
//width=392;
var noMore = false;
var pageNo = 0;
var pageSize = 9;
export default class SelectImage extends Component{
  static navigationOptions = ({ navigation }) =>{
    return{
      header:null,
      // title: '选择图片',
      // headerRight:(<View></View>),
      // headerLeft:<BackButton navigation = {navigation}/>
    }
  };
  constructor(props){
    super(props);
    this.state = ({
      column:4,
      type:1,  //1-素材， 2-背景， 3-我的图片
			topActive: 0,
      loading:false,
			activeTypeId:'',
			activeSecondTypeId:'',
      leftActive:0,
      leftData:[],
			imageSecondTypeList:[],
      data:[],
			userId: this.props.navigation.getParam('userId'),
    })
    //alert(width);
  }
  componentDidMount(){
    Orientation.lockToLandscape();
    pageNo = 0;
    noMore = false;
    this._getTypeList();
    // setTimeout(()=>{
    //   this._getTempList(0);
    // },100)
    
  }
	componentWillUnmount(){
		pageNo = 0;
    noMore = false;
	}
  onHeaderRefresh = () => {
    //alert('header')
  }
  onFooterRefresh = () => {
    //alert('header')
    console.log('noMore',noMore);
    console.log('--end')
    if(noMore){
  		return;
    }
    pageNo++;

    console.log('pageNo=',pageNo);
    //if(pageNo == 0 || pageNo == 1) return;
    if(this.state.type == 1){
      if(this.state.topActive == 0){ //全部
        this._getImageList(1);
      } else {
        this._getImageList(2);
        //this._getLensListTwo();
      }
    } else if(this.state.type == 2){
      this._getImageList(1);
    }
    
  	//this.fetchData(pageNo);
    this.setState({refreshState: RefreshState.FooterRefreshing});
  }
  _getTypeList(){
    fetch(BASEURL+'image/imageTypeList?pageNo=1&pageSize=1000&type='+this.state.type)
    .then(res=>res.json())
    .then(response=>{
      console.log(response);
      this.setState({
        leftData:response.list.result,
				activeTypeId:response.list.result[0].type_id
      },()=>{
        if(this.state.type == 1){ //素材
          this._getSecondTypeList(response.list.result[0].type_id);
        } else if(this.state.type == 2){//背景
          this.onFooterRefresh();
        }
        //this._getImageList(response.list.result[0].type_id);
				
      })
    })
  }
	//获取图片二级类型列表
  _getSecondTypeList(typeId){
    fetch(BASEURL+'image/getImageTypeSecondList?typeId='+typeId)
    .then(res=>res.json())
    .then(response=>{
      //console.log(response);
      if(response.succ == '1'){
        //alert('show)');
        this.setState({
          imageSecondTypeList:response.list,
          //showList: true,
        },()=>{
          this.onFooterRefresh();
					//pageNo = 1;
					//this._getLensList(lensTypeId);
        })
      }
    })
  }
  _getImageList(type){
    //this.refs.tipModal._loading();
		let typeId = this.state.activeTypeId;
		if(this.state.topActive != 0){
			typeId = this.state.activeSecondTypeId
		}
    fetch(BASEURL+'image/imageList?type='+type+'&typeId='+typeId+'&pageNo='+pageNo+'&pageSize='+pageSize)
    .then(res=>res.json())
    .then(result=>{
      this.refs.tipModal._close();
      console.log('list',result);
			if(result.succ == '1'){
        let data = this.state.data;
        if(pageNo == 1){
          data = [];
        }
        //console.log('length=',result.list.result.length)
        if(!result.list.result || result.list.result.length<pageSize ){
          noMore = true
          this.setState({
            data:data.concat(result.list.result),
            loading:false,
            refreshState: RefreshState.NoMoreData,
          })
        } else {
          this.setState({
            data:data.concat(result.list.result),
            loading:false,
            refreshState: RefreshState.Idle,
          })
        }
      }
    })
  }
	_getUserImageList(){
    //this.refs.tipModal._loading();
    let typeId = (this.state.leftActive+1);
    fetch(BASEURL+'image/userImageList?userId='+this.state.userId+'&typeId='+typeId+'&pageNo='+pageNo+'&pageSize='+pageSize)
    .then(res=>res.json())
    .then(result=>{
      this.refs.tipModal._close();
      console.log('list',result);
			if(result.succ == '1'){
        let data = this.state.data;
				let newData = [];
        if(pageNo == 1){
          newData.push(data[0]);
					data = newData;
        }
        //console.log('length=',result.list.result.length)
        if(!result.list.result || result.list.result.length<pageSize ){
          noMore = true
          this.setState({
            data:data.concat(result.list.result),
            loading:false,
            refreshState: RefreshState.NoMoreData,
          })
        } else {
          this.setState({
            data:data.concat(result.list.result),
            loading:false,
            refreshState: RefreshState.Idle,
          })
        }
      }
    })
  }
  _leftSelect(index,typeId){
    // this.setState({leftActive:index})
    // this._getImageList(typeId);
    noMore = false;
    pageNo = 0;
    if(this.state.type == 1){
      
      this.setState({
        data:[],
        topActive: 0,
        leftActive: index,
        activeTypeId: typeId,
        activeSecondTypeId: '',
      },()=>{
        this._getSecondTypeList(typeId);
      })
    } else if(this.state.type == 2){
      pageNo = 1;
      this.setState({
        data:[],
        topActive: 0,
        leftActive: index,
        activeTypeId: typeId,
      },()=>{
        this._getImageList(1);
      })
    } else { //我的图片
      pageNo = 1;
      this.setState({
        leftActive: index,
      },()=>{
        this._getUserImageList();
      })
    }
    
  }
  _selectImg(imageName,imageId){
    const {goBack,state} = this.props.navigation;
    state.params.callback(imageId);
    this.props.navigation.goBack(); 
  }
  //顶部3菜单切换
  topPress(type){
    noMore = false;
    pageNo = 0;
    this.setState({
      type: type,
      topActive:0,
      leftActive:0,
      data:[],
    },()=>{
      if(type == 1){//素材
        this._getTypeList();
      }else if(type == 2){//背景
        this.setState({
          //column:3
        },()=>{
          this._getTypeList();
        })
        
      } else { //我的图片
				pageNo = 1;
        let array = [];
        array.push({type_id :'1', type_name: '我的素材'});
        array.push({type_id :'2', type_name: '我的背景'})
        this.setState({
          leftData: array,
          data: [{type: 'add'}],
        },()=>{
					this._getUserImageList();
				})
      }
    })
  }
	//二级菜单类型点击
  secondTypeSelect(index,lensSecondType){
    this.setState({
      topActive:index,
      activeSecondTypeId:lensSecondType
    },()=>{
      noMore = false;
      pageNo = 1;
      if(index == 0){
        this._getImageList(1);
      } else {
        this._getImageList(2);
      }
    })
    
  }
  _addImage(type){
    ImagePicker.openPicker({
      width: 300,
      height: 300,
      cropping: false
    }).then(image => {
      console.log(image);
			this.uploadImage(image.path,type);
    });
  }
	uploadImage(imagePath, type){
    var url = BASEURL+'image/uploadImage';
    var formData = new FormData();
    var fileName = imagePath.substring(imagePath.lastIndexOf("/")+1,imagePath.length);
    let file = {uri: imagePath, type: 'multipart/form-data', name: fileName};
    formData.append("file",file);
    formData.append("userId", this.state.userId);
		formData.append("busType","1");
		formData.append("press",type);
		formData.append("typeId", this.state.leftActive+1);
		if(type == 2){
			formData.append("width",width);
			formData.append("height",height);
		}
    fetch(url,{
      method:'POST',
      headers:{
          'Content-Type':'multipart/form-data',
      },
      body:formData,
    })
    .then((response) => response.json() )
    .then((responseData)=>{
      //console.log('responseData',responseData);
      this._getUserImageList();
    })
    .catch((error)=>{
      console.error('error',error);
      this.refs.toast.show("上传失败");
    });
  }
  _renderLeft(){
    let leftData = this.state.leftData ;
		//alert(leftData.length)
    //if(leftData.length == 0) return;
    var leftCell = [];
    for(let i=0; i<leftData.length; i++){
      let item = leftData[i];
      leftCell.push(
        <TouchableOpacity key={i} onPress={()=>{this._leftSelect(i,item.type_id)}} activeOpacity={0.6}
          style={[styles.leftCell,i==this.state.leftActive?styles.leftCellActive:null]}>
          <Text style={{fontSize:16}}>{item.type_name}</Text>
        </TouchableOpacity>
      )
    }
    return leftCell;
  }
	renderSecondType(){
    let {imageSecondTypeList} = this.state;
    let array = [];
    let style={
      alignItems:'center',
      paddingLeft:8,
      paddingRight:8,
    }
		//let typeId = this.state.leftData[this.state.leftActive].type_id;
    array.push(
      <TouchableOpacity style={style} onPress={()=>this.secondTypeSelect(0)} key="0">
        <Text style={[{fontSize:this.state.topActive==0?17:15,padding:8,color:this.state.topActive==0?'#2596ff':'black'}]}>全部</Text>
        <View style={{height:2,width:20,backgroundColor:this.state.topActive==0?'#2596ff':'white'}}></View>
      </TouchableOpacity>
    )
    for(let i=0; i<imageSecondTypeList.length; i++){
      let item = imageSecondTypeList[i];
      array.push(
        <TouchableOpacity style={style} onPress={()=>this.secondTypeSelect(i+1,item.secondTypeId)} key={item.pkId}>
          <Text style={[{fontSize:this.state.topActive==(i+1)?17:15,padding:8,color:this.state.topActive==(i+1)?'#2596ff':'black'}]}>{item.typeName}</Text>
          <View style={{height:2,width:20,backgroundColor:this.state.topActive==(i+1)?'#2596ff':'white'}}></View>
        </TouchableOpacity>
      )
    }
    return array;
	}
	/** 
  _renderContent(){
    let {data} = this.state;
    var rightCell = [];
    for(let i=0; i<data.length; i++){
      let item = data[i];
      rightCell.push(
        <Cell  key={i}   style={{marginBottom:i==data.length-1?0:0}}
        press={()=>this._selectImg(item.newName)} data={item} />
      )
    }
    return rightCell;
	}
	*/
	_renderItem = ({item,index}) =>{
    //alert(1)
    let data = this.state.data;
    if(item.type && item.type == 'add'){
			if(this.state.leftActive == 1){
				return(
				<TouchableOpacity style={this.state.leftActive == 0?styles.cellViewStyle2:styles.cellViewStyle} activeOpacity={0.6} onPress={()=>{this._addImage(2)}}>
          <View style={[this.state.leftActive == 0?styles.cellImg2:styles.cellImg, {borderWidth:1,borderColor:'#ccc',backgroundColor:'#eee',justifyContent:'center',alignItems:'center'}]}>
            <Image style={{width:30,height:30}} source={require('../../images/temp/add_img.png')}/>
          </View>
        </TouchableOpacity>
				)
			}
      return(
        <TouchableOpacity style={this.state.leftActive == 0?styles.cellViewStyle2:styles.cellViewStyle} activeOpacity={0.6} onPress={()=>{this._addImage(1)}}>
          <View style={[this.state.leftActive == 0?styles.cellImg2:styles.cellImg, {borderWidth:1,borderColor:'#ccc',backgroundColor:'#eee',justifyContent:'center',alignItems:'center'}]}>
            <Image style={{width:30,height:30}} source={require('../../images/temp/add_img.png')}/>
          </View>
        </TouchableOpacity>
      )
    } else {
      let type = '';
			let imageName = item.new_name;
			let imageId = item.image_id;
			if(this.state.type == 3){//我的图片
        type = 'userImage';
        imageName = item.user_id+'/'+item.new_name;
			} else {
        type = this.state.type;
			}
			if(this.state.type == 1){//素材
				return(
					<Cell2  key={index}  type={type} style={{borderColor:'red',borderWidth:0}}
						press={()=>this._selectImg(imageName,imageId)}  data={item} />
				)
			} else if(this.state.type == 3 && this.state.leftActive == 0){//我的图片，我的素材
				return(
					<Cell2  key={index}  type={type} style={{borderColor:'red',borderWidth:0}}
						press={()=>this._selectImg(imageName,imageId)}  data={item} />
				)
			}
			return(
				<Cell  key={index}  type={type} style={{borderColor:'red',borderWidth:0}}
					press={()=>this._selectImg(imageName,imageId)}  data={item} />
			)
		}
  }
	_keyExtractor = (item, index) => index.toString();
	_keyExtractor2 = (item, index) => index.toString()+"_";
  _separator = () => {
    return <View style={{height:0,backgroundColor:'#f0f0f0'}}/>;
  }
  _onChange(val){
    this.setState({
      keyword: val,
    })
  }
  _search(){
    noMore = false;
    pageNo = 1;
    this._getImageList(1);
	}
	renderList(){
		if(this.state.type == 1 ||(this.state.type == 3 && this.state.leftActive == 0)){
			return(
				<RefreshListView
					key={this.state.type+this.state.leftActive}
					style={{flex:1,}}
					data={this.state.data}
					keyExtractor={this._keyExtractor2}
					renderItem={this._renderItem}
					refreshState={this.state.refreshState}
					onHeaderRefresh={this.onHeaderRefresh}
					onFooterRefresh={this.onFooterRefresh}
					ItemSeparatorComponent={this._separator}
					numColumns={7}
					// 可选
					footerRefreshingText= '数据加载中...'
					footerFailureText = '--数据加载失败--'
					footerNoMoreDataText= '--没有更多了--'
					/>
			)
		} else {
			return(
				<RefreshListView
					style={{flex:1,}}
					key={this.state.type+this.state.leftActive}
					data={this.state.data}
					keyExtractor={this._keyExtractor}
					renderItem={this._renderItem}
					refreshState={this.state.refreshState}
					onHeaderRefresh={this.onHeaderRefresh}
					onFooterRefresh={this.onFooterRefresh}
					ItemSeparatorComponent={this._separator}
					numColumns={3}
					// 可选
					footerRefreshingText= '数据加载中...'
					footerFailureText = '--数据加载失败--'
					footerNoMoreDataText= '--没有更多了--'
					/>
			)
		}
	}
  render(){
    //console.log('len',this.state.data.length)
    return(
      <View style={styles.container}>
        <View style={{height:50,flexDirection:'row',alignItems:'center'}}>
          <BackButton navigation = {this.props.navigation}/>
          <HeaderTitle title='素材' textColor={this.state.type==1?'#2596ff':'black'} 
            viewColor={this.state.type==1?'#2596ff':'white'}  press={()=>this.topPress(1)}/>
          <View style={{height:30,width:1,backgroundColor:'#aaa'}}></View>
          <HeaderTitle title='背景' textColor={this.state.type==2?'#2596ff':'black'} 
            viewColor={this.state.type==2?'#2596ff':'white'} press={()=>this.topPress(2)}/>
          <View style={{height:30,width:1,backgroundColor:'#aaa'}}></View>
          <HeaderTitle title='我的图片' textColor={this.state.type==3?'#2596ff':'black'} 
            viewColor={this.state.type==3?'#2596ff':'white'} press={()=>this.topPress(3)}/>

          <View style={{width:height/5*2}}>
            <Search placeholder='搜索图片...'
						search={()=>this._search()} 
						subStyle={{backgroundColor:'#f0f0f0',marginTop:5,paddingRight:5}}
            onChange={(val)=>this._onChange(val)}
            />
          </View>
        </View>
				<View style={{height:6,backgroundColor:'#f0f0f0'}}></View>
        <View style={styles.content}>
					<View style={styles.leftView}>
						<ScrollView showsVerticalScrollIndicator={false}>
							{this._renderLeft()}
						</ScrollView>
					</View>
          
          { this.state.loading ? <Loading/> : 
          (
            <View style={{borderWidth:0,borderColor:'black',flex:1}}> 
              {this.state.type==1?
							<View>
                <ScrollView horizontal={true} showsHorizontalScrollIndicator={false} style={{borderColor:'red',borderWidth:0,paddingTop:4,paddingBottom:4}}>
                  {this.renderSecondType()}
                </ScrollView>
              </View>:null
              }
							<ScrollView style={{flex:1}}>
								<View style={styles.rightView}>
								{/* {this._renderContent()} */}
								{
									this.renderList()	
								}
									
								</View>
							</ScrollView>
						</View>
          )
          
          }
        </View>
        <TipModal ref="tipModal"/>
      </View>
    )
  }
}
class Cell2 extends Component{
  render(){
    let imgUrl = BASEURL+'image/showImage?imageName='+ this.props.data.new_name;
    let botImg = require('../../images/temp/icon_confirm.png')
    //console.log('****',this.props.type);
		if(this.props.type == 'userImage'){
      imgUrl =  BASEURL+'image/showImage?imageName='+ this.props.data.user_id+'/'+this.props.data.new_name;
      botImg = require('../../images/mine/icon_del_nor.png')
		} else if(this.props.type == 1){
      //imgWidth = (height/8*7-30)/4;
    }
    console.log('imgUrl2',imgUrl);
    return(
      <View style={[styles.cellViewStyle2,this.props.style,]} activeOpacity={0.6} >
        <Image style={[styles.cellImg2,]}  source={{uri:imgUrl}}/>
        <View style={{flexDirection:"row", justifyContent:'space-between',alignItems:'center'}}>
          <Text style={[styles.cellText,{width:width5-20}]}
						numberOfLines={1} ellipsizeMode='tail'>{this.props.data.old_name}</Text>
          {
            this.props.type == 'userImage'?
            <TouchableOpacity onPress={this.props.delPress}>
              <Image resizeMode='contain' style={{width:14,height:14,marginRight:5}} source={botImg}/>
            </TouchableOpacity>:
            <TouchableOpacity onPress={this.props.press}>
              <Image resizeMode='contain' style={{width:14,height:14,marginRight:5}} source={botImg}/>
            </TouchableOpacity>
          }
          
        </View>
        
				{/* <Text style={styles.cellText}>{imgUrl}</Text> */}
      </View>
    )
  }
}
class Cell extends Component{
  render(){
    let imgUrl = BASEURL+'image/showImage?imageName='+ this.props.data.new_name;
		if(this.props.type == 'userImage'){
			imgUrl =  BASEURL+'image/showImage?imageName='+ this.props.data.user_id+'/'+this.props.data.new_name;
		} else if(this.props.type == 1){
      //imgWidth = (height/8*7-30)/4;
    }
    console.log('imgUrl2',imgUrl);
    return(
      <View style={[styles.cellViewStyle,this.props.style,]} activeOpacity={0.6} >
        <Image style={[styles.cellImg,]}  source={{uri:imgUrl}}/>
        <View style={{flexDirection:"row", justifyContent:'space-between',alignItems:'center'}}>
					<Text numberOfLines={1} ellipsizeMode='tail'
						style={[styles.cellText,{width:(height-120-30)/3-30}]}>{this.props.data.old_name}</Text>
          {
            this.props.type == "userImage"?
            <TouchableOpacity onPress={this.props.delPress}>
              <Image resizeMode='contain' style={{width:14,height:14,marginRight:5}} source={require('../../images/mine/icon_del_nor.png')}/>
            </TouchableOpacity>:
            <TouchableOpacity onPress={this.props.press}>
              <Image resizeMode='contain' style={{width:20,height:16,marginRight:5}} source={require('../../images/temp/icon_confirm.png')}/>
            </TouchableOpacity>
          }
          
        </View>
        
				{/* <Text style={styles.cellText}>{imgUrl}</Text> */}
      </View>
    )
  }
}
const styles = StyleSheet.create({
  cellViewStyle:{
    marginTop:10,
    marginLeft:5,
    width:(height-leftWidth-30)/3,
    //width:'25%',
    // backgroundColor:'#fff',
    // borderWidth:StyleSheet.hairlineWidth,
    borderColor:'black',
    paddingBottom:8,
	},
	cellViewStyle2:{
    marginTop:10,
    marginLeft:5,
    width: width5,//(height-120-30)/5,
    borderColor:'black',
    paddingBottom:8,
  },
  cellText:{
    padding:5,
	},
	cellImg2:{
    width: width5,//(height-120-30)/5,
    height: width5,//(height-120-30)/5,
		borderWidth:0,
		borderColor:'green'
  },
  cellImg:{
    width:(height-leftWidth-30)/3,
    height:(height-leftWidth-30)/3/16*9,
		borderWidth:0,
		borderColor:'green'
  },
  leftCell:{
    padding:15,
    paddingLeft:10,
    paddingRight:10,
    justifyContent:'center',
    alignItems:'center',
    backgroundColor:'#f0f0f0',
    borderLeftColor:'#f0f0f0',
    borderLeftWidth:4,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor:'#ccc',
  },
  leftCellActive:{
    backgroundColor:'#fff',
    borderLeftColor:'#2596ff',
  },
  leftView:{
    // borderWidth:1,
    // borderColor:'gray',
		//width:height/7,
		width:leftWidth,
  },
  rightView:{
    paddingLeft:0,
    // borderWidth:1,
    // borderColor:'green',
    flex:1,
    height:'100%',
    flexDirection:'row',
    flexWrap:'wrap',
  },
  content:{
    flexDirection:'row',
    flex:1,
    // borderWidth:1,
    // borderColor:'red',
  },
  headerText:{
    fontSize:18,
    color:'#000',
    padding:10,
  },
  container: {
    flex: 1
  },
})